<template>
  <a-modal
    width="80%"
    :visible="isModal"
    :footer="null"
    :maskClosable="false"
    :bodyStyle="{ height: '900px', overflow: 'auto' }"
    forceRender
    destroyOnClose
    @cancel="isModal = false"
  >
    <!--  -->
    <template slot="title">
      通用树配置
      <EchoConfig echo="tree" @f_echoChange="s_echoChange"/>
    </template>

    <!-- 标签页区域 -->
    <a-tabs v-if="isModal" v-model="tabKey" force-render @change="tabChange"   type="editable-card" @edit="onEdit">
      <a-tab-pane v-for="item in tabList" :key="item.label" :tab="item.label" :closable="true"> </a-tab-pane>
    </a-tabs>

    <!-- 编辑或回显区域 -->
    <div v-if="isModal" class="core">
      <!-- 左侧盒子 -->
      <div class="core_left">
        <TreeConfig v-if="treeConfig.length > 0" :gData="treeConfig" @f_setTreeData="s_setTreeData" @f_setTreeSelect="s_setTreeSelect" />
      </div>
      <!-- 右侧盒子 -->
      <div :key="rightKey" class="core_right">
        <!-- 全局属性 -->
        <a-col :span="14">
          <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="模态框标题" required>
            <a-input v-model="currentFa.label" style="width: 70%" placeholder="标题" />
          </a-form-model-item>
        </a-col>
        <a-col :span="10">
          <a-button @click="addItem" :style="{ marginRight: '8px' }" icon="save"> 重置 </a-button>
          <a-popconfirm
            title="确定删除吗？"
            ok-text="是"
            cancel-text="否"
            @confirm="delRecord(slotIndex)"
          >
            <a-button :style="{ marginRight: '8px' }" type="danger" icon="delete"> 删除 </a-button>
          </a-popconfirm>
          
          <a-button @click="saveRecord" :style="{ marginRight: '8px' }" type="primary" icon="save"> 保存 </a-button>
          <a-button @click="showJson()" type="primary" icon="save"> json </a-button>
        </a-col>
        <!-- 顶部属性配置 -->
        <div class="core_right_top">
          <Attribute />
        </div>
        <!-- 底部映射配置 -->
        <div class="core_right_bottom">
          <FieldList  />
        </div>
      </div>
    </div>

    <!-- json组件 -->
    <ShowJson ref="showJsonRef" />
  </a-modal>
</template>
<script>
import { currentFa, currentObj, setFavalue, setCurrentvalue, init, treeList, setTreeList } from '@/utils/formassembly/generaltree.js'
import { parseData,  parseSubtable} from '@/utils/component/parsetree.js'
export default {
  data() {
    return {
      tabKey: '', // tab栏key
      rightKey: 0, // 右侧盒子刷新标识
      currentFa: currentFa, // 原始对象
      currentObj: currentObj, // 原始对象
      cpCurrentObj: {}, // 拷贝对象
      cpCurrentFa: {}, // 拷贝对象
      treeConfig: [],
      labelCol: { span: 5 }, // label宽
      wrapperCol: { span: 18 }, // 组件宽
      // { label: '初始化', key: 'apl_table' }
      tabList: treeList,
      isModal: false,
    }
  },
  created() {
    // console.log('this.tabList', this.tabList, this.tabList.length, this.tabList.length > 0)
    if(this.tabList.length > 0) {
      setFavalue(JSON.parse(JSON.stringify(this.tabList[0])))
      this.currentFa = JSON.parse(JSON.stringify(this.tabList[0]))
      setCurrentvalue(JSON.parse(JSON.stringify(this.tabList[0].data[0] || {})))
      this.treeConfig = JSON.parse(JSON.stringify(this.tabList[0].data || []))
      this.cpCurrentFa = JSON.parse(JSON.stringify(this.tabList[0]))
      // this.rightKey ++
    }
    // console.log('currentFa', currentFa, this.currentFa)
    // console.log('currentObj', currentObj)
  },
  methods: {
    s_echoChange(treeList) {
      console.log('treeList', treeList)
      this.tabList = treeList
      setTreeList(JSON.parse(JSON.stringify(treeList)))
      this.treeConfig = treeList[0].data
    },
    // 新增一项 (清空就行了)
    addItem() {
      init()
      this.rightKey ++
    },
    // 显示配置json
    showJson() {
      this.$refs.showJsonRef.init(this.tabList)
    },
    // 标签页删除
    onEdit(targetKey, action) {
      if(action == 'remove') {
        let i = 0
        for(let v of this.tabList) {
          if(v.label == targetKey) {
            this.tabList.splice(i, 1)
          }
          i++
        }
      }
    },
    // 标签页切换
    tabChange(key) {
      // console.log('key', key)
      for(let v of this.tabList) {
        if(v.label == key) {
          setFavalue(v)
          this.currentFa = v
          setCurrentvalue(this.currentFa.data[0] || {})
          this.currentObj =  this.currentFa.data[0] || {}
          this.treeConfig = this.currentFa.data
          this.rightKey ++
          break
        }
      }
    },
    // 树节点选中回显
    s_setTreeSelect(data) {
      setCurrentvalue(JSON.parse(JSON.stringify(data)))
      this.rightKey ++
    },
    // 树组件拖动排序回调
    s_setTreeData(data) {
      console.log('树回显', data)
      this.cpCurrentFa.data = this.treeConfig = JSON.parse(JSON.stringify(data))
    },
    // 删除记录
    delRecord() {
      this.delTreeNode(this.treeConfig, currentObj.apltable)
      this.cpCurrentFa.data = this.treeConfig = [... this.treeConfig]
    },
    // 删除树节点
    delTreeNode(data, apltable) {
      data.map((v, i) => {
        if (v.apltable == apltable) {
          data.splice(i, 1)
          // console.log('找到了删除', v, i)
          return
        } else if (v.children && v.children.length > 0) {
          this.delTreeNode(v.children, apltable)
        }
      })
    },
    // 保存记录
    saveRecord() {
      if (!currentFa.label) {
        this.$message.warning('请输入模态框名称')
        return
      }
      if (!currentObj.apltable) {
        this.$message.warning('请选择申请表')
        return
      }
      if (currentObj.require == undefined) {
        this.$message.warning('请选择是否必填')
        return
      }
      if (!currentObj.label) {
        this.$message.warning('请输入节点标题')
        return
      }
      if (currentObj.isaddown == undefined) {
        this.$message.warning('请选择是否允许添加本级')
        return
      }
      if (!currentObj.span) {
        this.$message.warning('请输入一行几个')
        return
      }
      if (!currentObj.relationfield) {
        this.$message.warning('请选择申请表关联字段')
        return
      }
      if (!currentObj.entrelationfield) {
        console.log('---', currentObj.entrelationfield)
        this.$message.warning('请选择企业表关联字段')
        return
      }
      if (currentObj.isappend == undefined) {
        this.$message.warning('请选择是否补正')
        return
      }
      if (!currentObj.primary) {
        this.$message.warning('请选择显示字段')
        return
      }
      delete currentObj['children']
      // 解析数据
      
      let result = parseData(currentObj.fieldlist, currentObj.span)
      console.log('解析完成', result)
      currentObj.rules = result.rules
      currentObj.filters = result.filters
      currentObj.fill_item = result.fill_item
      currentObj.maprelation = result.maprelation
      console.log('保存currentObj', currentObj)
      // 解析从表
      if(currentObj.sublist && currentObj.sublist.length > 0) {
        for(let i=0; i<=currentObj.sublist.length-1; i++) {
          // console.log('从表', currentObj.sublist[i])
          let columns = parseSubtable(currentObj.sublist[i].fieldlist)
          currentObj.sublist[i].columns = columns
        }
      }
      this.cpCurrentObj = JSON.parse(JSON.stringify(currentObj))
      // console.log('this.cpCurrentObj', this.cpCurrentObj)
      // 更新左侧树数据
      let check = this.updateTree(this.treeConfig, currentObj.apltable)
      // console.log('check', check)
      if (check == false) {
        // console.log('新增树', this.cpCurrentObj)
        this.treeConfig.push(this.cpCurrentObj)
      }
      this.cpCurrentFa.data = JSON.parse(JSON.stringify(this.treeConfig))
      // 更新顶部页签
      this.updateTab()
      setTreeList(JSON.parse(JSON.stringify(this.tabList)))
      console.log('tabList', this.tabList)
    },
    // 更新左侧树数据
    updateTree(data, apltable) {
      let check = false
      data.map((v) => {
        if (v.apltable == apltable) {
          check = true
          for (let key in this.cpCurrentObj) {
              v[key] = this.cpCurrentObj[key]
          }
          // console.log('更新树', v)
          return
        } else if (v.children && v.children.length > 0) {
          check = this.updateTree(v.children, apltable)
        }
      })
      return check
    },
    // 更新顶部页签
    updateTab() {
      // 根据key有则更新
      for (let v of this.tabList) {
        if (v.label == this.currentFa.label) {
          console.log('this.cpCurrentFa', this.cpCurrentFa)
          v.data = JSON.parse(JSON.stringify(this.cpCurrentFa.data))
          // v.data = this.cpCurrentFa.data 
          this.$message.success('更新成功')
          this.tabKey = this.cpCurrentFa.label
          return
        }
      }
      // 没有进行新增
      this.cpCurrentFa = JSON.parse(JSON.stringify(this.currentFa))
      // 放入进顶级对象 (新增重置树数据)
      this.treeConfig = [this.cpCurrentObj]
      this.tabList.push(JSON.parse(JSON.stringify(this.cpCurrentFa)))
      this.tabKey = this.currentFa.label
      this.$message.success('保存成功')
    },
    // 父组件初始化
    async f_init() {
      // 初始化vuex 表数据的值
      await this.$store.dispatch('GETTABLES')
      this.isModal = true
    },
  },
  components: {
    TreeConfig: () => import('@/views/businessAssembly/generaltree/treeConfig.vue'),
    Attribute: () => import('@/views/businessAssembly/generaltree/attributeConfig.vue'),
    FieldList: () => import('@/views/businessAssembly/generaltree/fieldList.vue'),
    ShowJson: () => import('@/views/businessAssembly/public/spareparts/showJson.vue'),
    EchoConfig: () => import('@/views/businessAssembly/jsonComponent/base/echoConfig.vue')
  },
}
</script>

<style lang="less" scoped>
.btnBox {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 50px;
}
.core_right,
.core_left {
  border: 1px solid #eee;
  height: 100%;
}
.core_right_bottom,
.core_right_top {
  width: 100%;
  border: 1px solid rgb(247, 244, 244);
}
.core {
  // border: 1px solid red;
  height: 92%;
  display: flex;
  justify-content: space-between;
  &_left {
    width: 28%;
  }
  &_right {
    width: 70%;
    display: flex;
    flex-wrap: wrap;
    align-content: space-between;
    &_top {
      height: 24%;
      overflow: auto;
    }
    &_bottom {
      height: 68%;
      // overflow: auto;
      // border: 1px solid red;
    }
  }
}
</style>
